package com.hsq.commons.util.db.dbUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hsq.commons.util.DateUtil;
import com.hsq.commons.util.beans.BeanUtils;

public  class DbBeanUtil<T> {
	
	@SuppressWarnings("unused")
	private static Log log = LogFactory.getLog(DbBeanUtil.class);
	
	public static <T> T  parseBean(Map<String,Object> m,Class<T> clazz){		
		T t =  BeanUtils.newInstance(clazz);	
		if(m==null)return t;
		for (Map.Entry<String, Object> entry : m.entrySet()) { 
			  	Object o = entry.getValue();
			  	String key = DbStringUtil.replace(entry.getKey(), "_");
			  	//log.info(key);
			  	if(o==null ){
			  		continue;
			  	}
			  	else if (o instanceof String){
					//log.info(key+"  "+o.toString()+ " is String ."+o);
					BeanUtils.setFieldValue(t,key ,String.class, o);
				}
				else if (o instanceof Integer){
					//log.info(key+"  "+o.toString()+ " is Integer ."+((Integer)o).intValue());
					BeanUtils.set(t, key, o);
				}
				else if (o instanceof Long){
					//log.info(key+"  "+o.toString()+ " is Long ."+((Long)o).longValue());
					BeanUtils.set(t, key, o);
				}
				else if (o instanceof Short){
					//log.info(key+"  "+o.toString()+ " is short ."+((Short)o).shortValue());
					BeanUtils.set(t, key, o);
				}
				else if ( o instanceof Date ){
					//log.info(key+"  "+o.toString()+ " is date ."+((Date)o).getTime());
					BeanUtils.setFieldValue(t, key,String.class,DateUtil.parse((Date)o,"yyyy-MM-dd HH:mm:ss"));
				}else if ( o instanceof Float ){
					//log.info(key+"  "+o.toString()+ " is float ."+o);
					BeanUtils.set(t, key, o);
				}
				else{
					//log.info(key+"  "+o.toString()+ " is object .");
					BeanUtils.setFieldValue(t, key,String.class,o);
				}
		} 
		return t;
	}
	
	
	
	
	
	
	public static <T> List<T> parseList(List<Map<String,Object>> list,Class<T> clazz){
		List<T> l = new ArrayList<T>();
		 for (Map<String, Object> map : list) {
			 l.add(parseBean(map,clazz));
			 map = null;
		 }
		 return l;
	};
	
	
	
//	public static void main(String[] args){
//		CmsCatalogueBean t = new CmsCatalogueBean();
//		long o = 5;
//		BeanUtils.setFieldValue(t, "showType",Long.class, o);
//		System.out.println(t.getShowType());
//
//	}
	
}
